package com.hiof.location.earcon;

import android.media.MediaPlayer;
import com.hiof.Configuration;
import com.hiof.R;
import com.hiof.data.MoraService;
import com.hiof.servercommunication.background.job.listener.INextTargetLocationListener;
import com.hiof.servercommunication.receive.beans.GeoPoint;
import com.hiof.servercommunication.receive.beans.Packet;
import com.hiof.servercommunication.receive.beans.TargetInfoPacket;
import com.hiof.utility.Utility;

/**
 * Created with IntelliJ IDEA.
 * User: manish
 * Date: 4/20/12
 * Time: 8:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class EncourageNotificationManager extends EarconManager {
    private static EncourageNotificationManager instance;
    private boolean isPlayingSound = false;
    MediaPlayer player;

    public static EncourageNotificationManager getInstance() {
        if (instance == null) {
            instance = new EncourageNotificationManager();
        }
        return instance;
    }

    private EncourageNotificationManager() {
        isPlayingSound = false;
        player = MediaPlayer.create(Configuration.getInstance().getCurrentContext(), R.raw.cheer);
        player.setLooping(true);
    }

    private void startPlaying() {
        Utility.debug(this.getClass().toString(), "Start play sound for point: " + MoraService.getInstance().getNextTargetInfo().getTargetName());
        isPlayingSound = true;
        player.setLooping(true);
        setVolume(0.1f);
        player.start();
    }

    private void stopPlaying() {
        Utility.debug(this.getClass().toString(), "Stop play sound for point: " + MoraService.getInstance().getNextTargetInfo().getTargetName());
        isPlayingSound = false;
        player.pause();
    }

    private void setVolume(float volume) {
        player.setVolume(volume, volume);
    }

    @Override
    public void updateLocationChanged(GeoPoint geoPoint) {
        GeoPoint nextTargetPoint = MoraService.getInstance().getNextTargetInfo().getGeoPoint();
        if (nextTargetPoint == null)
            return;

        double distance = Utility.distanceByMeters(geoPoint, nextTargetPoint);
        Utility.debug(this.getClass().toString(), "Distance: " + distance);

        if (isPlayingSound) {
            if (distance < 100) {
                setVolume(1f);
            } else if (distance < 300 && distance >= 100) {
                setVolume(0.5f);
            } else if (distance < 700 && distance >= 300) {
                setVolume(0.1f);
            } else if (distance >= 700) {
                stopPlaying();
            }
        } else {
            if (distance < 700) {
                startPlaying();
            }
        }
    }

    @Override
    public void destroy() {
        stopPlaying();
        if (instance != null)
            instance = null;
    }
}
